Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/paste pictures into editor #472

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

caushcani
Copy link

@caushcani caushcani commented Dec 6, 2024

What kind of change does this PR introduce?

Feature: Enable pasting of pictures into the editor, with automatic upload and attachment.

Why was this change needed?

This feature was needed to streamline the process of adding images and videos to the editor. Currently, users must go through a more time-consuming method of uploading media, and this change aims to make the process faster by allowing images/videos to be pasted directly into the editor, automatically uploading them as media and attaching them.

Other information:

eg: Did you discuss this change with anybody before working on it (not required, but can be a good idea for bigger changes). Any plans for the future, etc?
Issue #390 and i discussed it with @nevo-david .

Checklist:

Put a "X" in the boxes below to indicate you have followed the checklist;

  • I have read the CONTRIBUTING guide.
  • I checked that there were not similar issues or PRs already open for this.
  • This PR fixes just ONE issue (do not include multiple issues or types of change in the same PR) For example, don't try and fix a UI issue and include new dependencies in the same PR.

Summary by CodeRabbit

  • New Features

    • Enhanced media upload capabilities across multiple components.
    • Added support for handling pasted media in the editor.
    • Improved metadata handling for uploaded files.
  • Bug Fixes

    • Streamlined media management by removing unnecessary local state, ensuring more efficient updates.
  • Documentation

    • Updated comments and structure to reflect changes in media handling processes.

Copy link

vercel bot commented Dec 6, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
gitroom ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 8, 2024 6:20pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
postiz ⬜️ Ignored (Inspect) Visit Preview Dec 8, 2024 6:20pm

Copy link

vercel bot commented Dec 6, 2024

@caushcani is attempting to deploy a commit to the Listinai Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

coderabbitai bot commented Dec 6, 2024

Walkthrough

The changes in this pull request involve updates to several components in the frontend application, primarily focusing on enhancing media upload functionality. A new entry is added to the .gitignore file to exclude the uploads directory from version control. Significant modifications are made to the AddEditModal and Editor components to support media uploads through Uppy, including new event handlers for paste events. Additionally, the media handling logic in MultiMediaComponent, MediaComponent, and MultipartFileUploaderAfter is streamlined to improve efficiency and reduce local state management.

Changes

File Path Change Summary
.gitignore Added uploads to ignore the uploads directory.
apps/frontend/src/components/launches/add.edit.model.tsx Updated AddEditModal to support media uploads using Uppy, added new imports, and modified related functions.
apps/frontend/src/components/launches/editor.tsx Added onPaste prop to CopilotTextarea for handling paste events.
apps/frontend/src/components/media/media.component.tsx Modified MultiMediaComponent and MediaComponent to rely on props for media management, removing local state.
apps/frontend/src/components/media/new.uploader.tsx Updated MultipartFileUploaderAfter to enhance upload process with metadata handling and improved response management.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Editor
    participant AddEditModal
    participant Uppy
    participant Server

    User->>Editor: Paste media
    Editor->>AddEditModal: Trigger onPaste
    AddEditModal->>Uppy: Initiate media upload
    Uppy->>Server: Upload media
    Server-->>Uppy: Return upload URL
    Uppy-->>AddEditModal: Notify upload success
    AddEditModal->>Editor: Update media state
Loading

🐰 "In the code, changes do hop,
Media uploads, now they won't stop!
With a paste, the files take flight,
Uppy helps them soar so bright.
Ignore the uploads, keep them clear,
A smoother path for all, my dear!" 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@caushcani
Copy link
Author

Hi @nevo-david , could you please take a look at this PR when you have time? Thank you!

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (5)
apps/frontend/src/components/launches/add.edit.model.tsx (5)

Line range hint 10-10: Avoid using @ts-ignore by providing TypeScript definitions

Instead of suppressing TypeScript errors with // @ts-ignore, consider installing type definitions for react-use-keypress or creating a custom declaration to ensure type safety.


391-391: Specify a more precise type for _file parameter

The _file parameter in uploadMediaToServer is currently typed as any. Specify a more precise type, such as File, to enhance type safety and code clarity.


396-396: Simplify allowedFileTypes initialization

Instead of splitting a string, define the allowedFileTypes array directly for better readability.

- allowedFileTypes: 'image/*,video/mp4'.split(','),
+ allowedFileTypes: ['image/*', 'video/mp4'],

413-413: Simplify null checks using optional chaining

You can simplify the null checks by using optional chaining:

- if (mediaToAdd && mediaToAdd.path && mediaToAdd.id) {
+ if (mediaToAdd?.path && mediaToAdd.id) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 413-413: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


532-532: Simplify null checks using optional chaining

Use optional chaining to simplify the condition:

- if (clipboardData && clipboardData.items) {
+ if (clipboardData?.items) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 532-532: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b263299 and 7058aa9.

📒 Files selected for processing (6)
  • .gitignore (1 hunks)
  • apps/frontend/src/components/launches/add.edit.model.tsx (5 hunks)
  • apps/frontend/src/components/launches/editor.tsx (1 hunks)
  • apps/frontend/src/components/media/media.component.tsx (3 hunks)
  • apps/frontend/src/components/media/new.uploader.tsx (2 hunks)
  • apps/frontend/src/components/settings/teams.component.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • .gitignore
  • apps/frontend/src/components/settings/teams.component.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
apps/frontend/src/components/launches/add.edit.model.tsx

[error] 413-413: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 532-532: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (3)
apps/frontend/src/components/launches/add.edit.model.tsx (1)

397-397: Verify if maxFileSize of 1GB is appropriate

The maxFileSize is set to 1GB (1000000000 bytes). Verify if allowing such large file uploads is appropriate, as it may impact performance and resource usage.

apps/frontend/src/components/launches/editor.tsx (1)

57-57: LGTM!

The addition of the onPaste prop effectively extends the CopilotTextarea to handle paste events.

apps/frontend/src/components/media/media.component.tsx (1)

226-231: Verify the impact of removing currentMedia state

By removing the currentMedia state and relying directly on value, ensure that the component behavior remains correct and there are no unintended side effects.

@@ -84,9 +85,13 @@ export function MultipartFileUploaderAfter({

uppy2.on('complete', (result) => {
onUploadSuccess(result);
console.log('uppy complete:', result)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove console.log statement from production code

Remove the console.log('uppy complete:', result); statement to prevent unnecessary logging in production.

Comment on lines 92 to 94
console.log('uppy upload success:file', file)
console.log('uppy upload success:response', response)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove console.log statements from production code

Remove these console.log statements to clean up the code:

- console.log('uppy upload success:file', file)
- console.log('uppy upload success:response', response)

const newMedia = [...(currentMedia || []), m];
setCurrentMedia(newMedia);
const newMedia = [...(value || []), m];
console.log('new media inside component', newMedia);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove debugging console.log statement

Remove the console.log('new media inside component', newMedia); used for debugging to keep the code clean.

@nevo-david
Copy link
Contributor

Hi @caushcani I have just tried it, it looks like it sends a request to Uppy but it's not attaching any files.
Can you make a video?

@caushcani
Copy link
Author

caushcani commented Dec 7, 2024

HI Nevo, here it is.
The image is uploaded and stored in the 'uploads' folder, and the path is also saved in the database.
P.S. Ignore the issue of images not being displayed, as I am facing a problem with serving static files (possibly with Caddy or another issue).

Screen-Recording.webm

Payload:
image

@nevo-david
Copy link
Contributor

Does it work for you with command / ctrl + v ?

@caushcani
Copy link
Author

caushcani commented Dec 7, 2024

Yes, it works. Can u send me a video how you paste the image and network request?
Video using ctrl+v:

Screen-Recording.1.webm

@caushcani
Copy link
Author

@nevo-david, I made an addition here. Can you try it now ?

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
apps/frontend/src/components/launches/add.edit.model.tsx (2)

530-557: Simplify clipboard data handling

The clipboard data handling can be simplified using optional chaining and array methods.

Consider this more concise implementation:

 onPaste={(event) => {
-  const clipboardData =
-    event.clipboardData ||
-    (
-      window as Window &
-        typeof globalThis & {
-          clipboardData: DataTransfer;
-        }
-    ).clipboardData;
-  if (clipboardData && clipboardData.items) {
-    for (const item of Array.from(clipboardData.items)) {
-      const mediaTypes = ['image', 'video'];
-
-      if (mediaTypes.some((type) => item.type.indexOf(type) !== -1)) {
-        const media = item.getAsFile();
-        if(media){
-          uploadMediaToServer(media, index);
-        }
-      }
-    }
-  }
+  const clipboardData = event.clipboardData ?? window?.clipboardData;
+  const mediaTypes = ['image', 'video'];
+  
+  Array.from(clipboardData?.items ?? [])
+    .filter(item => mediaTypes.some(type => item.type.startsWith(type)))
+    .forEach(item => {
+      const media = item.getAsFile();
+      if (media) {
+        uploadMediaToServer(media, index);
+      }
+    });
 }}
🧰 Tools
🪛 Biome (1.9.4)

[error] 539-539: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


292-297: Improve readability of character count validation

The nested conditions for character count validation could be simplified.

Consider this more readable approach:

-key.value.some((p) => {
-  return (
-    countCharacters(p.content, key?.integration?.identifier || '') >
-    (key.maximumCharacters || 1000000)
-  );
-})
+const maxChars = key.maximumCharacters ?? 1000000;
+const identifier = key.integration?.identifier ?? '';
+key.value.some(p => countCharacters(p.content, identifier) > maxChars)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6d90f3b and 948f27d.

📒 Files selected for processing (1)
  • apps/frontend/src/components/launches/add.edit.model.tsx (5 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
apps/frontend/src/components/launches/add.edit.model.tsx

[error] 413-413: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 539-539: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (1)
apps/frontend/src/components/launches/add.edit.model.tsx (1)

53-55: LGTM: Required imports added correctly

The new imports are properly structured and necessary for the media upload functionality.

Comment on lines +391 to +425
const uploadMediaToServer = (_file: File, index: number) => {
const uppy2 = new Uppy({
autoProceed: true,
restrictions: {
maxNumberOfFiles: 1,
allowedFileTypes: ['image/*', 'video/mp4'],
maxFileSize: 1000000000,
},
});

const { plugin, options } = getUppyUploadPlugin(
storageProvider,
fetch,
backendUrl
);
uppy2.use(plugin, options);
uppy2.addFile(_file);

uppy2.on('complete', (result) => {
if (result) {
const mediaToAdd = result?.successful![0].response?.body;

if (mediaToAdd && mediaToAdd.path && mediaToAdd.id) {
const newMedia: {
path: string;
id: string;
}[] = [
...(value[index].image || []),
{ path: mediaToAdd.path, id: mediaToAdd.id },
];
changeImage(index)({ target: { name: 'image', value: newMedia } });
}
}
});
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling and loading state management

While the upload implementation is functional, it could be improved with:

  1. Error handling for upload failures
  2. Loading state management to provide user feedback during uploads

Consider applying these improvements:

 const uploadMediaToServer = (_file: File, index: number) => {
+  const [isUploading, setIsUploading] = useState(false);
   const uppy2 = new Uppy({
     autoProceed: true,
     restrictions: {
       maxNumberOfFiles: 1,
       allowedFileTypes: ['image/*', 'video/mp4'],
       maxFileSize: 1000000000,
     },
   });

   const { plugin, options } = getUppyUploadPlugin(
     storageProvider,
     fetch,
     backendUrl
   );
   uppy2.use(plugin, options);
+  setIsUploading(true);
   uppy2.addFile(_file);

+  uppy2.on('upload-error', (file, error) => {
+    setIsUploading(false);
+    toaster.show(`Failed to upload ${file.name}: ${error.message}`, 'error');
+  });

   uppy2.on('complete', (result) => {
+    setIsUploading(false);
     if (result) {
       const mediaToAdd = result?.successful![0].response?.body;

       if (mediaToAdd && mediaToAdd.path && mediaToAdd.id) {
         const newMedia: {
           path: string;
           id: string;
         }[] = [
           ...(value[index].image || []),
           { path: mediaToAdd.path, id: mediaToAdd.id },
         ];
         changeImage(index)({ target: { name: 'image', value: newMedia } });
+      } else {
+        toaster.show('Invalid response from server', 'error');
       }
     }
   });
 };

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 413-413: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Copy link

@A1exKH A1exKH left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@caushcani code LGTM.
Please resolve conflicts for that PR.

@caushcani
Copy link
Author

@A1exKH solved.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
apps/frontend/src/components/launches/add.edit.model.tsx (1)

573-600: Simplify paste handler implementation

The paste handler works correctly but could be more maintainable.

Consider these improvements:

-onPaste={(event) => {
-  const clipboardData =
-    event.clipboardData ||
-    (
-      window as Window &
-        typeof globalThis & {
-          clipboardData: DataTransfer;
-        }
-    ).clipboardData;
-  if (clipboardData && clipboardData.items) {
-    for (const item of Array.from(clipboardData.items)) {
-      const mediaTypes = ['image', 'video'];
-
-      if (mediaTypes.some((type) => item.type.indexOf(type) !== -1)) {
-        const media = item.getAsFile();
-        if(media){
-          uploadMediaToServer(media, index);
-        }
-      }
-    }
-  }
-}}
+onPaste={(event) => {
+  const SUPPORTED_MEDIA_TYPES = ['image/', 'video/mp4'];
+  const items = event.clipboardData?.items ?? window.clipboardData?.items;
+  
+  if (!items) return;
+  
+  Array.from(items).forEach(item => {
+    if (SUPPORTED_MEDIA_TYPES.some(type => item.type.startsWith(type))) {
+      const media = item.getAsFile();
+      if (media) {
+        uploadMediaToServer(media, index);
+      }
+    }
+  });
+}}
🧰 Tools
🪛 Biome (1.9.4)

[error] 582-582: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 948f27d and 5e513d2.

📒 Files selected for processing (1)
  • apps/frontend/src/components/launches/add.edit.model.tsx (4 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
apps/frontend/src/components/launches/add.edit.model.tsx

[error] 436-436: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 582-582: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (2)
apps/frontend/src/components/launches/add.edit.model.tsx (2)

53-55: LGTM: Required imports added for media upload functionality.

The new imports provide the necessary dependencies for implementing the image paste feature.


414-448: 🛠️ Refactor suggestion

Add error handling and loading state management

While the upload implementation is functional, it needs improvements:

  1. Error handling for upload failures
  2. Loading state management
  3. Optional chaining for safer null handling

Consider applying these improvements:

 const uploadMediaToServer = (_file: File, index: number) => {
+  const [isUploading, setIsUploading] = useState(false);
   const uppy2 = new Uppy({
     autoProceed: true,
     restrictions: {
       maxNumberOfFiles: 1,
       allowedFileTypes: ['image/*', 'video/mp4'],
       maxFileSize: 1000000000,
     },
   });

   const { plugin, options } = getUppyUploadPlugin(
     storageProvider,
     fetch,
     backendUrl
   );
   uppy2.use(plugin, options);
+  setIsUploading(true);
   uppy2.addFile(_file);

+  uppy2.on('upload-error', (file, error) => {
+    setIsUploading(false);
+    toaster.show(`Failed to upload ${file.name}: ${error.message}`, 'error');
+  });

   uppy2.on('complete', (result) => {
+    setIsUploading(false);
-    if (result) {
-      const mediaToAdd = result?.successful![0].response?.body;
+    const mediaToAdd = result?.successful?.[0]?.response?.body;

-      if (mediaToAdd && mediaToAdd.path && mediaToAdd.id) {
+      if (mediaToAdd?.path && mediaToAdd?.id) {
         const newMedia: {
           path: string;
           id: string;
         }[] = [
           ...(value[index].image || []),
           { path: mediaToAdd.path, id: mediaToAdd.id },
         ];
         changeImage(index)({ target: { name: 'image', value: newMedia } });
+      } else {
+        toaster.show('Invalid response from server', 'error');
       }
-    }
   });
 };

Likely invalid or redundant comment.

🧰 Tools
🪛 Biome (1.9.4)

[error] 436-436: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants